package com.wdemo.memory;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.wdemo.utils.MessageUtil;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.data.redis.core.BoundListOperations;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName RedisChatMemory
 * @Description 基于Redis的聊天内存
 * @Author WDEMO
 * @Date 2025/8/29 12:08
 */
public class RedisChatMemory implements ChatMemory {

    // 默认redis中key的前缀
    public static final String DEFAULT_PREFIX = "CHAT:";

    private String prefix;

    private final StringRedisTemplate stringRedisTemplate;

    public RedisChatMemory(String prefix,StringRedisTemplate stringRedisTemplate) {
        this.prefix = prefix;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public RedisChatMemory(StringRedisTemplate stringRedisTemplate) {
        this(DEFAULT_PREFIX,stringRedisTemplate);
    }
    @Override
    public void add(String conversationId, List<Message> messages) {
        if (CollUtil.isEmpty(messages)) {
            return;
        }
        var key = this.getKey(conversationId);
        var listOps = stringRedisTemplate.boundListOps(key);

        // 将消息序列化并添加到Redis列表的右侧
        messages.forEach(message -> listOps.rightPush(MessageUtil.toJson(message)));
    }

    @Override
    public List<Message> get(String conversationId) {
        if (ObjectUtil.isNull(conversationId)){
            return List.of();
        }
        String key = this.getKey(conversationId);
        // 获取Redis列表操作对象
        BoundListOperations boundListOps = stringRedisTemplate.boundListOps(key);
        List<String> range = boundListOps.range(0, -1);
        // 将Redis返回的字符串列表转换为Message对象列表
        List<Message> collect = range.stream()
                .map(r -> MessageUtil.toMessage(r))
                .collect(Collectors.toList());
        return collect;
    }

    @Override
    public void clear(String conversationId) {
        var redisKey = this.getKey(conversationId);
        this.stringRedisTemplate.delete(redisKey);
    }

    /**
     * 获取redis中key
     * @param conversationId 会话id
     * @return
     */
    private String getKey(String conversationId) {
        return this.prefix + conversationId;
    }
}
